/**
 *
 * @param {boolean} canImport - 导入按钮权限
 * @param {boolean} loading - 导入按钮加载状态
 * @param {function} url - 上传地址
 * @param {function} onSearch - 搜索函数
 *
 */

import { useState, useEffect } from 'react';
import { Button, Upload, Modal } from 'antd';
import { TRMessage } from '#/components';
import {
  DownloadOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
} from '#/utils/antdIcons';
import { useTRState } from '#/utils/trHooks';
import { TJModel } from '@/pages/ETrade/components';
import styles from './index.less';
import { HttpCode } from '#/utils/contacts';

const { Dragger } = Upload;

const TjImportBtn = (props) => {
  const { canImport, loading, url, onSearch } = props;

  const importList = url;

  const [fileInfo, setFileInfo] = useState(null);

  const [state, setState] = useTRState({
    finallyFile: [], // 最终保存文件
    saveType: 0, // 确认按钮状态
    visible: false, // 导入弹窗展示
    isShowMore: false, // 是否展示更多
    btnLoading: false, // 弹窗确认按钮loading
    fileError: null, // 文件错误信息
    uploadDate: '', // 上传时间
  });

  // 上传文件配置
  const draggerProps = {
    name: 'file',
    multiple: false,
    showUploadList: false,
    accept: '.pdf',
    maxCount: 1,
  };

  useEffect(() => {
    const formatDate = () => {
      return new Date().toLocaleString();
    };
    setState({
      uploadDate: formatDate(),
    });
  }, [state.finallyFile]);

  const _beforeUpload = (file) => {
    if (!file.uid) {
      file.uid = Date.now();
    }
    if (!file.status) {
      file.status = 'done';
    }
    // 通过FileReader对象读取文件
    const fileReader = new FileReader();

    fileReader.onload = async (event) => {
      const { result } = event.target;
      const isPDF = file.type === 'application/pdf';

      if (!isPDF) {
        setState({
          fileError: ['请上传正确文件!'],
        });
        if (file.status) {
          file.status = 'error';
        }
        setFileInfo(file);
        return false;
      }
      setFileInfo(file);
      setState({
        saveType: 1,
        finallyFile: file,
      });
    };

    fileReader.readAsArrayBuffer(file);
    return false;
  };

  const onImport = () => {
    // 导入数据
    if (!canImport) return TRMessage.info('请联系管理员获取相关权限');
    setState({
      visible: true,
    });
  };

  const onClose = () => {
    setFileInfo(null);
    setState({
      visible: false,
      saveType: 0,
      fileError: null,
      btnLoading: false,
    });
  };

  const importHandle = async () => {
    if (btnLoading) return;
    setState({
      btnLoading: true,
    });
    const { finallyFile } = state;
    const formData = new FormData();
    formData.append('file', finallyFile);
    const res = await importList(formData);
    if (res?.statusCode === HttpCode.SUCCESS) {
      TRMessage.success('导入成功');
      onClose();
      onSearch();
    } else {
      TRMessage.error(res?.message || '导入失败');
      const errorMessage = res?.data || res?.message || '导入失败';
      setState({
        fileError: [errorMessage],
      });
    }
    setState({
      btnLoading: false,
    });
  };

  const formatSize = (size) => {
    if (size < 1024) return `${size} B`;
    if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`;
    return `${(size / (1024 * 1024)).toFixed(2)} MB`;
  };

  const handleDelete = () => {
    setFileInfo(null);
    setState({ saveType: 0, fileError: null });
  };

  const { visible, btnLoading, saveType, isShowMore, fileError, uploadDate } = state;

  return (
    <>
      <Button
        style={{ padding: 0 }}
        className={`${!canImport && styles.disabled}`}
        type="link"
        icon={<DownloadOutlined />}
        onClick={onImport}
        loading={loading}
      >
        导入
      </Button>
      <TJModel
        title={'导入'}
        width={530}
        visible={visible}
        onCancel={onClose}
        footer={[
          <Button key="back" onClick={onClose}>
            取消
          </Button>,
          !!saveType && (
            <Button key="submit" type="primary" loading={btnLoading} onClick={importHandle}>
              提交
            </Button>
          ),
        ]}
      >
        <div className={styles.content}>
          <div className={styles.label}>
            导入文件
            <span className={styles.after}>仅支持PDF文件</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'center', flexDirection: 'column' }}>
            {!fileInfo ? (
              <div
                style={{
                  width: '481px',
                  height: '160px',
                  border: '1px dashed var(--bd-a50)',
                  borderRadius: '5px',
                }}
              >
                <Dragger {...draggerProps} beforeUpload={_beforeUpload}>
                  <p className={styles.label}>
                    <span className={styles.down}>点击上传</span>
                    <span className={styles.after_text}>/ 拖拽到此区域</span>
                  </p>
                </Dragger>
              </div>
            ) : (
              <>
                <div
                  className={styles.file_box}
                  style={
                    fileInfo?.status === 'done' && !fileError
                      ? { border: '1px dashed var(--bd-a30)' }
                      : { border: '1px dashed #c12929' }
                  }
                >
                  <div className={styles.file_info}>
                    <p className={styles.label}>
                      {fileInfo?.name}{' '}
                      {fileInfo?.status === 'done' && !fileError ? (
                        <CheckCircleOutlined
                          style={{ color: 'rgb(82, 196, 26)', marginLeft: '10px' }}
                        />
                      ) : (
                        <ExclamationCircleOutlined style={{ color: 'red', marginLeft: '10px' }} />
                      )}
                    </p>
                    <p className={styles.after_text}>文件大小:{formatSize(fileInfo?.size)}</p>
                    <p className={styles.after_text}>上传日期: {uploadDate}</p>
                    <div style={{ paddingTop: '13px' }}>
                      <span className={styles.file_footer} onClick={handleDelete}>
                        删除
                      </span>
                    </div>
                  </div>
                </div>
                {fileError && (
                  <div style={{ color: '#c12929', marginTop: '4px' }}>
                    {JSON.stringify(fileError)?.slice(1, -2).substring(1, 20)}
                    {JSON.stringify(fileError).slice(1, -2)?.length > 20 && (
                      <>
                        ......
                        <span
                          className={styles.more}
                          onClick={() => setState({ isShowMore: true })}
                        >
                          更多
                        </span>
                      </>
                    )}
                  </div>
                )}
                <Modal
                  width={720}
                  className={styles.modal}
                  centered={true}
                  visible={isShowMore}
                  onOk={() => {
                    setState({ isShowMore: false });
                  }}
                  onCancel={() => {
                    setState({ isShowMore: false });
                  }}
                  maskClosable={true}
                  title={
                    <div key="title" className={styles.modal_title}>
                      文件上传错误内容查看
                    </div>
                  }
                >
                  {fileError &&
                    fileError.length > 0 &&
                    fileError.map((v, i) => {
                      return <div key={i}>{v};</div>;
                    })}
                </Modal>
              </>
            )}
          </div>
        </div>
      </TJModel>
    </>
  );
};

export default TjImportBtn;
